import axios from "axios";
import { useAuthStore } from "@/stores/auth";

class Http {
  constructor() {
    this.instance = axios.create({
      baseURL: import.meta.env.VITE_BASE_URL,
      timeout: 6000,
    });

    this.instance.interceptors.request.use((config) => {
      const authStore = useAuthStore();
      const token = authStore.token;
      if (token) {
        config.headers["Authorization"] = "JWT " + token;
      }
      return config;
    });
  }

  post(path, data) {
    // return this.instance.post(path, data)
    return new Promise(async (resolve, reject) => {
      // await：网络请求发送出去后，线程会挂起这个等待
      // 等网络数据到达后，线程又会回到当前位置继续执行
      // 如果在某个函数中使用了await，某个函数就必须要定义为async函数
      // axios底层也是用的Promise函数，在相应状态码不是200的情况下，就会调用reject掉
      // 调用reject后，外层函数会抛出异常
      try {
        let result = await this.instance.post(path, data);
        // 走到这里，说明状态码是200
        resolve(result.data);
      } catch (error) {
        // 走到catch中，说明状态码肯定不是200
        let detail = error.response.data.detail;
        reject(detail);
      }
    });
  }

  get(path, params) {
    return new Promise(async (resolve, reject) => {
      try {
        let result = await this.instance.get(path, { params });
        resolve(result.data);
      } catch (err) {
        let detail = err.response.data.detail;
        reject(detail);
      }
    });
  }

  put(path, data) {
    return new Promise(async (resolve, reject) => {
      try {
        let result = await this.instance.put(path, data);
        resolve(result.data);
      } catch (error) {
        let detail = error.response.data.detail;
        reject(detail);
      }
    });
  }

  delete(path) {
    return new Promise(async (resolve, reject) => {
      try {
        let result = await this.instance.delete(path);
        // 服务端的delete方法，只返回一个状态码，并没有数据，所以直接把result返回就可以了
        resolve(result);
      } catch (error) {
        let detail = error.response.data.detail;
        reject(detail);
      }
    });
  }

  downloadFile(path, params) {
    return new Promise(async (resolve, reject) => {
      try {
        let result = await this.instance.get(path, { 
          params,
          responseType: "blob" // 设置响应类型为 blob
         });
        resolve(result);
      } catch (err) {
        let detail = err.response.data.detail;
        reject(detail);
      }
    });
  }
}

export default new Http();
